<template>
  <div class="question-container">
    <!-- 头部区域 -->
    <el-card>
      <div class="addbtn-wrap">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="small"
          @click="$router.push('/questions/new')"
        >
          新增试题
        </el-button>
      </div>
      <el-form :model="form">
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科" label-width="80px">
              <el-select
                v-model="form.subjectID"
                placeholder="请选择"
                style="width:100%"
                @change="onLoadChange"
              >
                <el-option
                  v-for="(item, index) in subjectList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录" label-width="80px">
              <el-select
                v-model="form.catalogID"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="(item, index) in catelogList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签" label-width="80px">
              <el-select
                v-model="form.tags"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="(item, index) in tagsList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字" label-width="80px">
              <el-input
                placeholder="根据题干搜索"
                style="width:100%"
                v-model="form.keyword"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="试题类型" label-width="80px">
              <el-select
                v-model="form.questionType"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="(item, index) in questionType"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度" label-width="80px">
              <el-select
                v-model="form.difficulty"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="(item, index) in difficulty"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向" label-width="80px">
              <el-select
                v-model="form.direction"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="(item, index) in direction"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人" label-width="80px">
              <el-select
                v-model="form.creatorID"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="(item, index) in creatorList"
                  :key="index"
                  :label="item.username"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="题目备注" label-width="80px">
              <el-input v-model="form.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称" label-width="80px">
              <el-input v-model="form.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市" label-width="80px">
              <el-select
                v-model="form.province"
                placeholder="请选择"
                size="small"
                style="width: 48%; margin-right: 2%;"
                @change="onCityChange"
              >
                <el-option
                  v-for="(item, index) in provinces"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.city"
                placeholder="请选择"
                size="small"
                style="width:50%"
              >
                <el-option
                  v-for="(item, index) in citys"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="btn-search-clear">
            <el-button size="mini" @click="clearForm">清除</el-button>
            <el-button type="primary" size="mini" @click="searchQuestion">
              搜索
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-alert
        :title="`数据一共${total}条`"
        type="info"
        show-icon
        :closable="false"
        class="alert-text"
      >
      </el-alert>

      <!-- 基础题库列表 -->
      <el-table style="width: 100%" :data="baseList">
        <el-table-column prop="number" label="试题编号" width="120px">
        </el-table-column>
        <el-table-column prop="subject" label="学科" width="120px">
        </el-table-column>
        <el-table-column prop="catalog" label="目录"> </el-table-column>
        <el-table-column prop="questionType" label="题型">
          <template slot-scope="scope">
            {{ isQuestionType(scope.row.questionType) }}
          </template>
        </el-table-column>
        <el-table-column prop="question" label="题干" width="220px">
          <template slot-scope="scope">
            <span v-html="scope.row.question"></span>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间" width="200px">
          <template slot-scope="scope">
            {{ scope.row.addDate | parseTimeByString }}
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度">
          <template slot-scope="scope">
            {{ isDifficulty(scope.row.difficulty) }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人" width="120px">
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="预览"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-view"
                circle
                plain
                @click="showViewDialog(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="修改"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="success"
                icon="el-icon-edit"
                circle
                plain
                @click="goNewPage(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                plain
                @click="removeQuestionById(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="加入精选"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-check"
                circle
                plain
                @click="addChoiceById(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="queryInfo.pagesize"
        layout="prev, pager, next, sizes, jumper"
        :total="total"
        background
      >
      </el-pagination>

      <!-- 试题预览 -->
      <el-dialog
        v-if="viewDialogVisible"
        title="题目预览"
        width="70%"
        class="view-dialog"
        :visible.sync="viewDialogVisible"
      >
        <questions-preview
          :questionID="viewSubjectId"
          @close="viewDialogVisible = false"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { list, remove, choiceAdd } from '../../api/hmmm/questions'
import { simple } from '../../api/hmmm/subjects'
import { simple as label } from '../../api/hmmm/tags'
import { provinces, citys } from '../../api/hmmm/citys'
import { simple as creator } from '../../api/base/users'
import { simple as catelog } from '../../api/hmmm/directorys'
import { questionType, difficulty, direction } from '../../api/hmmm/constants'

import questionsPreview from '../components/questions-preview'

export default {
  components: { questionsPreview },
  data() {
    return {
      queryInfo: {
        page: 1,
        pagesize: 5
      },
      total: 0, // 基础题条数
      form: {
        subjectID: '',
        catalogID: '',
        tags: '',
        questionType: '',
        difficulty: '',
        direction: '',
        keyword: '',
        remarks: '', // 题目备注
        province: '', // 企业所在省份
        city: '', // 企业所在城市
        shortName: '', // 企业简称
        creatorID: '' // 录入人
      },
      creatorList: [], // 录入人列表
      subjectList: [], // 学科列表
      catelogList: [], // 二级目录列表
      tagsList: [], // 标签目录
      questionType: questionType, // 试题类型
      difficulty: difficulty, // 难度
      direction: direction, // 方向
      citys: [], // 城市列表
      provinces: [], // 城市下地区
      baseList: [], // 基础题库列表
      viewDialogVisible: false, // 控制预览试题弹框
      viewSubjectId: ''
    }
  },
  created() {
    // 初始化
    this.loadInitList()
    // 获取基础试题列表
    this.loadBaselist()
  },
  methods: {
    async loadInitList() {
      const subjectList = await simple(this.form)
      const creatorList = await creator()
      const provincesList = provinces()
      this.creatorList = creatorList.data
      this.subjectList = subjectList.data
      this.provinces = provincesList

      // console.log(res)
      // console.log(provincesList)
      // console.log(res)
    },
    async loadBaselist() {
      try {
        const { data: res } = await list(this.queryInfo)
        // console.log(res)
        this.baseList = res.items
        this.total = res.counts
      } catch (error) {
        this.$message('数据加载失败')
      }
    },
    async onLoadChange() {
      // console.log(this.form.subjectID)
      const catelogList = await catelog({
        subjectID: this.form.subjectID
      })
      const tagsList = await label()
      this.catelogList = catelogList.data
      this.tagsList = tagsList.data
    },
    onCityChange() {
      const cityList = citys(this.form.province)
      this.citys = cityList
    },
    // 清除表单数据
    clearForm() {
      this.form = this.$options.data().form
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.loadBaselist()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.loadBaselist()
    },
    // 搜索题型
    async searchQuestion() {
      try {
        const { data: res } = await list(this.searchForm)
        console.log(this.searchForm)
        // console.log(res)
        this.baseList = res.items
        this.total = res.counts
      } catch (error) {
        this.$message('搜索失败')
      }
    },
    // 显示预览试题对话框
    showViewDialog(row) {
      // console.log(row)
      this.viewDialogVisible = true
      this.viewSubjectId = row.id
    },
    // 删除试题
    async removeQuestionById(row) {
      const resultConfirm = await this.$confirm(
        '此操作将永久删除该题目, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(resultConfirm)
      // 如果点击确认按钮  返回字符串 confirm
      // 如果点击取消按钮  返回字符串 cancel
      if (resultConfirm !== 'confirm') return this.$message.info('已取消删除')

      try {
        await remove({
          id: row.id
        })
        // console.log(res)
        this.$message.success('删除成功！')
        this.loadBaselist()
      } catch (error) {
        // console.log(error)
        this.$message.error('删除失败！')
      }
    },
    // 加入精选
    async addChoiceById(row) {
      const resultConfirm = await this.$confirm(
        '此操作将该题目加入精选, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).catch(err => err)
      // console.log(resultConfirm)
      // 如果点击确认按钮  返回字符串 confirm
      // 如果点击取消按钮  返回字符串 cancel
      if (resultConfirm !== 'confirm') return this.$message.info('已取消操作')

      try {
        const { data: res } = await choiceAdd({
          id: row.id,
          choiceState: 1
        })
        console.log(res)
        this.$message.success('加入成功！')
        this.loadBaselist()
      } catch (error) {
        // console.log(error)
        this.$message.error('删除失败！')
      }
    },
    goNewPage(row) {
      this.$router.push({ path: '/questions/new', query: { id: row.id } })
    }
  },
  computed: {
    // 题型
    isQuestionType() {
      return function(val) {
        if (val === '1') {
          return '单选'
        } else if (val === '2') {
          return '多选'
        } else {
          return '简答'
        }
      }
    },
    // 难度
    isDifficulty() {
      return function(val) {
        if (val === '1') {
          return '简单'
        } else if (val === '2') {
          return '一般'
        } else {
          return '困难'
        }
      }
    },
    // 搜索表单项
    searchForm() {
      const searchData = {}
      for (const k in this.form) {
        if (this.form[k]) {
          searchData[k] = this.form[k]
        }
      }

      return searchData
    }
  }
}
</script>

<style scoped lang="scss">
.question-container {
  padding: 0 10px;
  margin: 10px 0;
}

.addbtn-wrap {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;

  .state-text {
    font-size: 12px;
    color: pink;
  }
}

.btn-search-clear {
  text-align: right;
  padding-top: 8px;
}

.alert-text {
  margin-bottom: 15px;
}

.pagination {
  text-align: right;
  margin-top: 15px;
}

.view-dialog {
  .el-col {
    padding: 10px 0;
  }
}
</style>
